<template>
  <div class="menus-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>菜单管理</span>
          <el-button type="primary" @click="openCreate">新增菜单</el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="名称">
          <el-input v-model="searchForm.name" placeholder="菜单名称" clearable />
        </el-form-item>
        <el-form-item label="路径">
          <el-input v-model="searchForm.path" placeholder="菜单路径" clearable />
        </el-form-item>
        <el-form-item label="ACL">
          <el-input v-model="searchForm.acl" placeholder="访问控制" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">搜索</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 列表 -->
      <el-table :data="menus" v-loading="loading" border stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="path" label="路径" />
        <el-table-column prop="order" label="排序" width="100" />
        <el-table-column prop="acl" label="ACL" width="320" />
        <el-table-column label="操作" width="220">
          <template #default="{ row }">
            <el-button size="small" @click="openDetail(row)">详情</el-button>
            <el-button size="small" type="primary" @click="openEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="onDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next, sizes, total"
          :total="pagination.total"
          :page-size="pagination.pageSize"
          :current-page="pagination.page"
          @size-change="onPageSizeChange"
          @current-change="onPageChange"
        />
      </div>
    </el-card>

    <!-- 错误提示 -->
    <el-alert
      v-if="menuStore.error"
      :title="menuStore.error"
      type="error"
      show-icon
      closable
      @close="menuStore.clearError"
      style="margin-top: 16px"
    />

    <!-- 对话框 -->
    <CreateMenuDialog v-model:visible="createVisible" @submit="handleCreate" />
    <EditMenuDialog v-model:visible="editVisible" :menu="currentMenu" @submit="handleUpdate" />
    <MenuDetailDialog v-model:visible="detailVisible" :menuId="detailId" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { useMenuStore } from "@/stores/menu";
import CreateMenuDialog from "./components/CreateMenuDialog.vue";
import EditMenuDialog from "./components/EditMenuDialog.vue";
import MenuDetailDialog from "./components/MenuDetailDialog.vue";

const menuStore = useMenuStore();
const menus = computed(() => menuStore.menus);
const loading = menuStore.loading;

const pagination = reactive({
  total: 0,
  page: 1,
  pageSize: 10,
  totalPages: 1,
});

const searchForm = reactive({
  name: "",
  path: "",
  acl: "",
});

const createVisible = ref(false);
const editVisible = ref(false);
const detailVisible = ref(false);
const currentMenu = ref<any>(null);
const detailId = ref<number | null>(null);

const fetchList = async () => {
  const res = await menuStore.fetchMenus({
    page: pagination.page,
    pageSize: pagination.pageSize,
    name: searchForm.name || undefined,
    path: searchForm.path || undefined,
    acl: searchForm.acl || undefined,
  });
  pagination.total = res.total;
  pagination.totalPages = res.totalPages;
};

const onSearch = async () => {
  pagination.page = 1;
  await fetchList();
};
const onReset = async () => {
  searchForm.name = "";
  searchForm.path = "";
  searchForm.acl = "";
  pagination.page = 1;
  await fetchList();
};

const onPageChange = async (page: number) => {
  pagination.page = page;
  await fetchList();
};
const onPageSizeChange = async (size: number) => {
  pagination.pageSize = size;
  pagination.page = 1;
  await fetchList();
};

const openCreate = () => (createVisible.value = true);
const openEdit = (menu: any) => {
  currentMenu.value = menu;
  editVisible.value = true;
};
const openDetail = (menu: any) => {
  detailId.value = menu.id;
  detailVisible.value = true;
};

const onDelete = async (menu: any) => {
  try {
    await ElMessageBox.confirm(`确认删除菜单 "${menu.name}" ?`, "警告", { type: "warning" });
    await menuStore.deleteMenu(menu.id);
    ElMessage.success("删除成功");
    await fetchList();
  } catch (e) {
    // 用户取消或失败
  }
};

const handleCreate = async (data: { name: string; path: string; order: string; acl: string }) => {
  await menuStore.createMenu(data);
  createVisible.value = false;
  ElMessage.success("创建成功");
  await fetchList();
};

const handleUpdate = async (data: { id: number; name?: string; path?: string; order?: string; acl?: string }) => {
  await menuStore.updateMenu(data.id, { name: data.name, path: data.path, order: data.order, acl: data.acl });
  editVisible.value = false;
  ElMessage.success("更新成功");
  await fetchList();
};

onMounted(fetchList);
</script>

<style lang="scss" scoped>
.menus-page {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .search-form {
    margin-bottom: 12px;
  }
  .pagination {
    margin-top: 12px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
